package com.leo.boot.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;

import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;
import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;
import static com.fasterxml.jackson.databind.DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL;
import static com.fasterxml.jackson.databind.SerializationFeature.FAIL_ON_EMPTY_BEANS;
import static com.fasterxml.jackson.databind.SerializationFeature.WRITE_SELF_REFERENCES_AS_NULL;
import static java.util.TimeZone.getDefault;

@Slf4j
@UtilityClass
public class JacksonUtils {

    public static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        objectMapper.setTimeZone(getDefault());
        objectMapper.setDefaultPropertyInclusion(NON_NULL);
        objectMapper.configure(WRITE_SELF_REFERENCES_AS_NULL, true);
        objectMapper.configure(FAIL_ON_EMPTY_BEANS, false);
        objectMapper.configure(READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
        objectMapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @SneakyThrows
    public static <T> T fromJson(String json, Class<T> clazz) {
        return objectMapper.readValue(json, clazz);
    }

    @SneakyThrows
    public static <T> String toJson(Object obj) {
        return objectMapper.writeValueAsString(obj);
    }
}
